package com.jefe.bamboo;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Sonali Mendis
 * Bamboo Portlet for Jefe (http://www.jefesolutions.com)
 * GNU License
 */
public class Driver {

    private ArrayList<BambooProject> project;
    private String error = null;
    private String host = null;
    private int port = 0;
    private String fil = null;
    private String user = null;
    private String pass = null;

    public Driver(){
        project = new ArrayList<BambooProject>();
    }
    public ArrayList<BambooProject> setProject(String hostApp, int portApp, String filter, String currentUser, String currentPass) throws SAXException, ParserConfigurationException, IOException{
        try{
            this.fil = filter;
            this.host = hostApp;
            this.port = portApp;
            this.user = currentUser;
            this.pass = currentPass;

            System.out.println("filter: " + fil);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse("http://"+host+":"+port+"/rest/api/latest/build.xml?os_authType=basic&os_username="+user+"&os_password="+pass);

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("build");
            System.out.println("No of builds present "+nList.getLength());

            Boolean found = false;
            for (int temp = 0; temp < nList.getLength(); temp++) {
                System.out.println(temp+" is in");
                Node nNode = nList.item(temp);
                if(nNode.getNodeType()==Node.ELEMENT_NODE){
                    BambooProject bp = new BambooProject();
                    Element eElement = (Element) nNode;
                    String key = eElement.getAttribute("key");
                    //partial string match to check fil is in the key
                    String searchFrom = key;
                    searchFrom = searchFrom.toUpperCase();
                    String toSearch = fil;
                    toSearch = toSearch.toUpperCase();

                    if(fil.equals("*")){
                        found = true;
                        String state = eElement.getAttribute("state");
                        String url = "http://"+host+":"+port+"/browse/"+key;
                        bp.setProjectName(key);
                        bp.setLastBuildStatus(state);
                        bp.setProjectURL(url);
                        project.add(bp);
                    }else{
                        int searchFromLength = searchFrom.length();
                        int toSearchLength = toSearch.length();
                        for (int i = 0; i <= (searchFromLength - toSearchLength); i++) {
                           if (searchFrom.regionMatches(i, toSearch, 0, toSearchLength)) {
                                found = true;
                                System.out.println("found!");
                                String state = eElement.getAttribute("state");
                                String url = "http://"+host+":"+port+"/browse/"+key;
                                bp.setProjectName(key);
                                bp.setLastBuildStatus(state);
                                bp.setProjectURL(url);
                                project.add(bp);
                           }
                        }
                    }
                }
            }
            if(!found){
                error = " This user can not access the project given in the Project Filter or the project doesn't exist.";
            }
        }catch(UnknownHostException ex){
            error = "The Remote host can not be detected.";
        }catch(Exception ex){
            error = ex.getMessage();
            ex.printStackTrace();
        }
        return project;
    }

     public String getErrors(){
        if(error==null){
            if(project.size()==0){
                error = "No projects for the user \""+user+"\" in this repository.";
            }
        }
        return error;
    }
}
